package com.ouyy.volunteerservice.volunteer.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ouyy.volunteerservice.volunteer.domain.po.Evaluation;
import com.ouyy.volunteerservice.volunteer.domain.po.Organizations;
import com.ouyy.volunteerservice.volunteer.mapper.EvaluationMapper;
import com.ouyy.volunteerservice.volunteer.mapper.OrganizationsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
public class UpdateScoreTask {

    @Autowired
    private EvaluationMapper evaluationMapper;

    @Autowired
    private OrganizationsMapper organizationsMapper;

    /**
     * 每 3 小时执行一次，计算每个 organization_id 的平均评分，并更新组织表
     */
    @Scheduled(cron = "*/30 * * * * ?")
    public void updateOrganizationScore() {
        System.out.println("【定时任务】更新组织平均评分...");

        try {
            // 查询所有组织 ID
            List<String> organizationIds = organizationsMapper.getAllOrganizationIds();

            for (String organizationId : organizationIds) {
                // 1. 查询该组织的所有评分
                QueryWrapper<Evaluation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("organization_id", organizationId);

                List<Evaluation> evaluations = evaluationMapper.selectList(queryWrapper);

                if (evaluations.isEmpty()) {
                    System.out.println("组织 " + organizationId + " 没有评分数据，跳过...");
                    continue;
                }

                // 2. 计算平均值
                BigDecimal totalScore = BigDecimal.ZERO;
                for (Evaluation evaluation : evaluations) {
                    totalScore = totalScore.add(BigDecimal.valueOf(evaluation.getScore()));
                }
                BigDecimal avgScore = totalScore.divide(BigDecimal.valueOf(evaluations.size()), 2, BigDecimal.ROUND_HALF_UP);
                System.out.println("平均分为："+avgScore);
                // 3. 更新组织表中的评分
                UpdateWrapper<Organizations> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("organization_id", organizationId).set("star_rating", avgScore);
                organizationsMapper.update(null, updateWrapper);

                System.out.println("【定时任务】组织 " + organizationId + " 的平均评分更新为：" + avgScore);
            }

        } catch (Exception e) {
            System.err.println("【定时任务】更新失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
